USE[DeltaFlex]
GO
IF(OBJECT_ID('dbo.sp_CercarAlbarans')IS NOT NULL)
	DROP PROCEDURE dbo.sp_CercarAlbarans
GO

CREATE PROCEDURE dbo.sp_CercarAlbarans
	@IDCLIENT smallint,
	@IDORDRE smallint = null,
	@DATAINICI date,
	@DATAFI date
AS
BEGIN
	 
	DECLARE  @S_SELECT varchar(1000);
	DECLARE  @S_WHERE varchar(1000);
	DECLARE  @S_COMMAND varchar(1000);

	 SET NOCOUNT ON 

	SET @S_SELECT  = 'SELECT IDALBARA, IDORDRE, IDCLIENT, DATA, TOTAL';
	SET @S_SELECT  = @S_SELECT + ' FROM ALBARA';

	SET @S_WHERE = ' WHERE IDCLIENT = '+ CAST(@IDCLIENT AS nvarchar(100));

	IF @IDORDRE IS NOT NULL
		SET @S_WHERE = @S_WHERE + ' AND IDORDRE  = ' + CAST(@IDORDRE AS varchar(100));

	IF @DATAINICI > '01/01/1950 0:00:00'
		SET @S_WHERE = @S_WHERE + ' AND DATA BETWEEN ''' +  CAST(@DATAINICI AS varchar(100)) + ''' AND ''' + CAST(@DATAFI AS varchar(100))+ '''';  


	SET @S_COMMAND = @S_SELECT + @S_WHERE;

	/*
	INSERT INTO dbo.LOGS(IDLOG, SPROCEDURE, SMISSATGE,DATA)
				 VALUES (NEXT VALUE FOR SEQ_LOG, 'dbo.sp_CercarAlbarans', @S_COMMAND, GETDATE());
	*/
	EXEC(@S_COMMAND);

	END 
GO

